package org.hit.burkun.umls;

import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.hit.burkun.db.DBHelper;
import org.hit.burkun.entities.Entity;

/**
 * 
 CREATE ALGORITHM = UNDEFINED DEFINER = `root`@`%` SQL SECURITY DEFINER VIEW
 * `uniport_ids_hgnc_id_cui` AS SELECT DISTINCT `b`.`uniport_ids` AS
 * `uniport_ids`, `b`.`hgnc_id` AS `hgnc_id`, `a`.`cui` AS `cui` FROM
 * (`biodata`.`hgnc_umls_mapping` `a` JOIN `biodata`.`hgnc_complete_set` `b`)
 * WHERE ((`a`.`hgnc_id` = `b`.`hgnc_id`) AND (`b`.`uniport_ids` IS NOT NULL));
 * 
 * CREATE ALGORITHM = UNDEFINED DEFINER = `root`@`%` SQL SECURITY DEFINER VIEW
 * `hgnc_umls_mapping` AS SELECT DISTINCT `a`.`hgnc_id` AS `hgnc_id`, `b`.`CUI`
 * AS `cui` FROM (`biodata`.`hgnc_complete_set` `a` JOIN `umls`.`MRCONSO` `b` ON
 * ((`a`.`hgnc_id` = `b`.`CODE`))) WHERE ((`a`.`status` = 'Approved') AND
 * (`b`.`SAB` = 'HGNC'));
 * 
 * CREATE ALGORITHM = UNDEFINED DEFINER = `root`@`%` SQL SECURITY DEFINER VIEW
 * `gene_id_hgnc_id_cui` AS SELECT DISTINCT `b`.`entrez_id` AS `entrez_id`,
 * `b`.`hgnc_id` AS `hgnc_id`, `a`.`cui` AS `cui` FROM
 * (`biodata`.`hgnc_umls_mapping` `a` JOIN `biodata`.`hgnc_complete_set` `b`)
 * WHERE ((`a`.`hgnc_id` = `b`.`hgnc_id`) AND (`b`.`entrez_id` IS NOT NULL));
 * 
 * 
 * @author burkun
 * 
 */
public class GeneIdUmlsMapper extends BaseMapper {

	public GeneIdUmlsMapper(DBHelper dbh, MapidsUmlsDump mapDbh) {
		super(dbh, null);
		this.mapDbh = mapDbh;
	}

	private MapidsUmlsDump mapDbh;
	private String mapPath = "gene_id=>hgnc=>umls";
	private Entity.TYPE type = Entity.TYPE.GENE_ID;

	@Override
	public void process(Map<String, Set<String>> data) {
		// 保存到数据库
		mapDbh.saveMappedToDb(type, data, mapPath);
	}

	public void quickMap() {
		// 不获取UniproKB的id，直接从视图中抽取插入到umls中
		String sqlStr = "select entrez_id, hgnc_id, cui from gene_id_hgnc_id_cui";
		Collection<String[]> res = dbh.queryData(sqlStr, 3);
		Map<String, Set<String>> data = new HashMap<>();
		for (String[] line : res) {
			String uniportIDs = line[0];
			// String hgnc = line[1];
			String cui = line[2];
			String[] ids = uniportIDs.split(",");
			for (String id : ids) {
				// uniport
				if (data.containsKey(id)) {
					data.get(id).add(cui);
				} else {
					Set<String> vs = new HashSet<>();
					vs.add(cui);
					data.put(id, vs);
				}
			}
		}
		process(data);
	}

	public static void main(String[] args) {
		DBHelper dbhData = DBHelper.getServerData();;
		MapidsUmlsDump mapDb = new MapidsUmlsDump(dbhData, "map_umls_ids");
		GeneIdUmlsMapper mapper = new GeneIdUmlsMapper(dbhData, mapDb);
		mapper.begin();
		mapper.quickMap();
		mapper.end();
	}

}
